<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="tall-form" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../HealthDisease.data';
  import { saveOrUpdate, getDepartName, queryAllTreeListByPid } from '../HealthDisease.api';
  import { defHttp } from '/@/utils/http/axios';

  // 存储项目组树形数据，用于查找节点名称
  let modalProjectTreeData: any[] = [];
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const currentHospital = ref();
  const hospitalOptions = ref<any[]>([]);

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema, getFieldsValue }] = useForm({
    //labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    
    // 加载医院选项
    await loadHospitalOptions();
    
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
      currentHospital.value = data.record?.hospital;

      if (data.record?.hospital) {
        const hospitalId = data.record.hospital;
        const hospital = hospitalOptions.value.find(item => item.value === hospitalId);
        if (hospital && hospital.sysOrgCode) {
          await loadProjectTree(hospital.sysOrgCode, hospitalId);
        }
      }
    } else {
      // 新增时，设置初始状态
      currentHospital.value = undefined;
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });

    // 设置表单值监听
    setupFormWatch();
  });
  // 加载医院选项
  async function loadHospitalOptions() {
    try {
      const result = await defHttp.get({
        url: '/nurse_hospital/nurseHospital/rootList',
        params: {
          pageNo: 1,
          pageSize: 9999,
        },
      });
      if (result && result.records && Array.isArray(result.records)) {
        hospitalOptions.value = result.records.map((item) => ({
          value: item.id,
          label: item.name,
          sysOrgCode: item.sysOrgCode,
        }));
      }
    } catch (error) {
      // 加载失败
    }
  }

  // 加载项目组树形数据
  async function loadProjectTree(sysOrgCode, hospitalId) {
    try {
      const departResult = await getDepartName({ orgCode: sysOrgCode });

      if (departResult && departResult.id) {
        const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
        const treeData = convertToTreeData(treeResult || []);
        modalProjectTreeData = treeData;

        updateSchema([
          {
            field: 'projectid',
            componentProps: {
              treeData: treeData,
              disabled: false,
              placeholder: '请选择项目组',
            },
          }
        ]);
      }
    } catch (error) {
      // 加载失败
    }
  }

  // 转换部门数据为树形选择器格式
  function convertToTreeData(data) {
    if (!Array.isArray(data)) return [];

    return data.map((item) => {
      const nodeId = item.id || item.key || item.value;
      const nodeTitle = item.departName || item.name || item.title || item.label;

      return {
        title: nodeTitle,
        key: nodeId,
        value: nodeId,
        children: item.children && item.children.length > 0 ? convertToTreeData(item.children) : undefined,
      };
    });
  }

  // 存储上一次的项目组ID，用于检测变化
  const previousProjectId = ref();

  // 监听表单值变化
  function setupFormWatch() {
    const timer = setInterval(() => {
      const values = getFieldsValue();
      
      if (values.hospital !== currentHospital.value && values.hospital !== undefined) {
        const newHospitalId = values.hospital;
        currentHospital.value = newHospitalId;

        setFieldsValue({ 
          projectid: undefined,
          projectname: undefined,
        });
        previousProjectId.value = undefined;

        const hospital = hospitalOptions.value.find(item => item.value === newHospitalId);
        if (hospital && hospital.sysOrgCode) {
          loadProjectTree(hospital.sysOrgCode, newHospitalId);
        } else {
          updateSchema([
            {
              field: 'projectid',
              componentProps: {
                treeData: [],
                disabled: true,
                placeholder: '请先选择医院',
              },
            },
          ]);
        }
      }
      
      if (values.projectid !== previousProjectId.value && values.projectid !== undefined) {
        const projectId = values.projectid;
        previousProjectId.value = projectId;
        
        const findNode = (nodes, targetValue) => {
          if (!nodes || !Array.isArray(nodes)) return null;
          for (const node of nodes) {
            if (node.value === targetValue || node.key === targetValue) {
              return node;
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children, targetValue);
              if (found) return found;
            }
          }
          return null;
        };
        
        if (modalProjectTreeData && modalProjectTreeData.length > 0) {
          const foundNode = findNode(modalProjectTreeData, projectId);
          
          if (foundNode) {
            const projectName = foundNode.title || foundNode.departName || foundNode.label || '';
            
            if (projectName && values.projectname !== projectName) {
              setFieldsValue({ projectname: projectName });
            }
          }
        }
      }
    }, 300);

    // 60秒后清理定时器
    setTimeout(() => clearInterval(timer), 60000);
  }

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values, isUpdate.value);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }

  /** 增加表单高度 */
  .tall-form {
    :deep(.ant-form) {
      max-height: 1200px;
      overflow-y: auto;
    }
  }

  /** 确保下拉框正确显示 */
  :deep(.ant-select-dropdown) {
    z-index: 9999 !important;
  }
</style>